package model

import "serialnet/sys/serial"

type AppConfig struct {
	Rs232Config   *SerialPara `json:"-"`
	Rs485Config   *SerialPara `json:"-"`
	MaxPacketSize int32       `json:"max_packet_size"`
	MaxBacklog    int32       `json:"max_backlog"`
	PacketNum     int         `json:"packet_num"`
	MaxWorker     int         `json:"max_worker"`
	EnableLog     bool        `json:"enable_log"`
	SaveLog       bool        `json:"save_log"`
	LogLevel      LogType     `json:"log_level"`
}

type SerialPara struct {
	LedIO      string
	ListenPort int
	Name       string
	Baud       int   // 1200 2400 4800 9600 19200 38400 57600 115200
	Parity     uint8 // N0, E2, O3, S4, M5,
	DataBits   uint8 // 5 6 7 8
	StopBits   uint8 // 1 3(1.5) 2
}

func SerialPara2Config(para *SerialPara) *serial.Config {
	if para == nil {
		return nil
	}
	config := &serial.Config{}
	config.Baud = para.Baud
	config.Name = para.Name
	config.Size = para.DataBits
	switch para.StopBits {
	case 1:
		config.StopBits = serial.Stop1
	case 2:
		config.StopBits = serial.Stop2
	case 3:
		config.StopBits = serial.Stop1Half
	default:
		config.StopBits = serial.Stop1
	}
	switch para.Parity {
	case 0:
		config.Parity = serial.ParityNone
	case 1:
		config.Parity = serial.ParityEven
	case 2:
		config.Parity = serial.ParityOdd
	case 3:
		config.Parity = serial.ParitySpace
	case 4:
		config.Parity = serial.ParityMark
	default:
		config.Parity = serial.ParityNone
	}
	config.ReadTimeout = 0
	return config
}

func SerialConfig2Para(config *serial.Config) *SerialPara {
	if config == nil {
		return nil
	}
	para := &SerialPara{}
	para.Name = config.Name
	para.Baud = config.Baud
	para.DataBits = config.Size
	switch config.Parity {
	case serial.ParityNone:
		para.Parity = 0
	case serial.ParityEven:
		para.Parity = 2
	case serial.ParityOdd:
		para.Parity = 3
	case serial.ParitySpace:
		para.Parity = 4
	case serial.ParityMark:
		para.Parity = 5
	}
	switch config.StopBits {
	case serial.Stop1:
		para.StopBits = 1
	case serial.Stop2:
		para.StopBits = 2
	case serial.Stop1Half:
		para.StopBits = 3
	}
	return para
}
